package com.yzxb.erpsystem.service.impl;

import com.yzxb.erpsystem.entity.PurchaseOrder;
import com.yzxb.erpsystem.entity.PurchaseOrderItem;
import com.yzxb.erpsystem.mapper.PurchaseOrderItemMapper;
import com.yzxb.erpsystem.mapper.PurchaseOrderMapper;
import com.yzxb.erpsystem.service.PurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class PurchaseOrderServiceImpl implements PurchaseOrderService {
    
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    
    @Autowired
    private PurchaseOrderItemMapper purchaseOrderItemMapper;
    
    @Override
    @Transactional
    public PurchaseOrder createPurchaseOrder(PurchaseOrder purchaseOrder) {
        // 非空校验
        if (purchaseOrder == null) {
            throw new IllegalArgumentException("采购订单不能为空");
        }
        
        if (purchaseOrder.getOrderCode() == null || purchaseOrder.getOrderCode().trim().isEmpty()) {
            throw new IllegalArgumentException("订单编号不能为空");
        }
        
        if (purchaseOrder.getSupplierId() == null) {
            throw new IllegalArgumentException("供应商ID不能为空");
        }
        
        if (purchaseOrder.getOrderDate() == null) {
            throw new IllegalArgumentException("下单日期不能为空");
        }
        
        if (purchaseOrder.getOrderStatus() == null || purchaseOrder.getOrderStatus().trim().isEmpty()) {
            throw new IllegalArgumentException("订单状态不能为空");
        }
        
        // 检查订单编号是否已存在
        if (purchaseOrderMapper.countByOrderCode(purchaseOrder.getOrderCode()) > 0) {
            throw new IllegalArgumentException("订单编号已存在");
        }
        
        // 计算订单总金额
        calculateTotalAmount(purchaseOrder);
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        purchaseOrder.setCreatedTime(now);
        purchaseOrder.setUpdatedTime(now);
        
        // 保存订单
        purchaseOrderMapper.insert(purchaseOrder);
        
        // 保存订单明细
        if (purchaseOrder.getOrderItems() != null && !purchaseOrder.getOrderItems().isEmpty()) {
            for (PurchaseOrderItem item : purchaseOrder.getOrderItems()) {
                item.setOrderId(purchaseOrder.getId());
                purchaseOrderItemMapper.insert(item);
            }
        }
        
        return purchaseOrder;
    }
    
    @Override
    @Transactional
    public PurchaseOrder updatePurchaseOrder(Long id, PurchaseOrder purchaseOrder) {
        // 非空校验
        if (id == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        
        if (purchaseOrder == null) {
            throw new IllegalArgumentException("采购订单不能为空");
        }
        
        // 查找原订单
        PurchaseOrder existingOrder = purchaseOrderMapper.selectById(id);
        if (existingOrder == null) {
            throw new RuntimeException("未找到订单，ID: " + id);
        }
        
        // 更新订单信息
        existingOrder.setSupplierId(purchaseOrder.getSupplierId());
        existingOrder.setExpectedDeliveryDate(purchaseOrder.getExpectedDeliveryDate());
        existingOrder.setActualDeliveryDate(purchaseOrder.getActualDeliveryDate());
        existingOrder.setCreatedBy(purchaseOrder.getCreatedBy());
        existingOrder.setUpdatedBy(purchaseOrder.getUpdatedBy());
        existingOrder.setRemark(purchaseOrder.getRemark());
        
        // 更新订单明细
        if (purchaseOrder.getOrderItems() != null) {
            // 删除原有明细
            purchaseOrderItemMapper.deleteByOrderId(id);
            
            // 添加新明细
            if (!purchaseOrder.getOrderItems().isEmpty()) {
                for (PurchaseOrderItem item : purchaseOrder.getOrderItems()) {
                    item.setOrderId(id);
                }
                purchaseOrderItemMapper.batchInsert(purchaseOrder.getOrderItems());
            }
            
            // 重新计算总金额
            calculateTotalAmount(purchaseOrder);
            existingOrder.setTotalAmount(purchaseOrder.getTotalAmount());
        }
        
        // 更新时间
        existingOrder.setUpdatedTime(LocalDateTime.now());
        
        purchaseOrderMapper.update(existingOrder);
        
        // 重新查询订单以获取最新数据
        return purchaseOrderMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public void deletePurchaseOrder(Long id) {
        // 非空校验
        if (id == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        
        // 检查订单是否存在
        PurchaseOrder existingOrder = purchaseOrderMapper.selectById(id);
        if (existingOrder == null) {
            throw new RuntimeException("未找到订单，ID: " + id);
        }
        
        // 先删除订单明细
        purchaseOrderItemMapper.deleteByOrderId(id);
        
        // 再删除订单
        purchaseOrderMapper.deleteById(id);
    }
    
    @Override
    public Optional<PurchaseOrder> getPurchaseOrderById(Long id) {
        // 非空校验
        if (id == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        
        PurchaseOrder order = purchaseOrderMapper.selectById(id);
        if (order == null) {
            throw new RuntimeException("未找到订单，ID: " + id);
        }
        return Optional.ofNullable(order);
    }
    
    @Override
    public Optional<PurchaseOrder> getPurchaseOrderByOrderCode(String orderCode) {
        // 非空校验
        if (orderCode == null || orderCode.trim().isEmpty()) {
            throw new IllegalArgumentException("订单编号不能为空");
        }
        
        PurchaseOrder order = purchaseOrderMapper.selectByOrderCode(orderCode);
        if (order == null) {
            throw new RuntimeException("未找到订单，订单编号: " + orderCode);
        }
        return Optional.ofNullable(order);
    }
    
    @Override
    public List<PurchaseOrder> getAllPurchaseOrders() {
        List<PurchaseOrder> orders = purchaseOrderMapper.selectAll();
        if (orders.isEmpty()) {
            throw new RuntimeException("未找到任何采购订单");
        }
        return orders;
    }
    
    @Override
    @Transactional
    public PurchaseOrder submitPurchaseOrder(Long id) {
        // 非空校验
        if (id == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        
        // 查找订单
        PurchaseOrder order = purchaseOrderMapper.selectById(id);
        if (order == null) {
            throw new RuntimeException("未找到订单，ID: " + id);
        }
        
        // 检查订单状态
        if (!"DRAFT".equals(order.getOrderStatus())) {
            throw new IllegalStateException("只有草稿状态的订单才能提交");
        }
        
        // 更新订单状态
        purchaseOrderMapper.updateStatus(id, "SUBMITTED");
        
        // 重新查询订单以获取最新数据
        return purchaseOrderMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public PurchaseOrder approvePurchaseOrder(Long id) {
        // 非空校验
        if (id == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        
        // 查找订单
        PurchaseOrder order = purchaseOrderMapper.selectById(id);
        if (order == null) {
            throw new RuntimeException("未找到订单，ID: " + id);
        }
        
        // 检查订单状态
        if (!"SUBMITTED".equals(order.getOrderStatus())) {
            throw new IllegalStateException("只有已提交状态的订单才能审核");
        }
        
        // 更新订单状态
        purchaseOrderMapper.updateStatus(id, "APPROVED");
        
        // 重新查询订单以获取最新数据
        return purchaseOrderMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public PurchaseOrder rejectPurchaseOrder(Long id) {
        // 非空校验
        if (id == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        
        // 查找订单
        PurchaseOrder order = purchaseOrderMapper.selectById(id);
        if (order == null) {
            throw new RuntimeException("未找到订单，ID: " + id);
        }
        
        // 检查订单状态
        if (!"SUBMITTED".equals(order.getOrderStatus())) {
            throw new IllegalStateException("只有已提交状态的订单才能拒绝");
        }
        
        // 更新订单状态
        purchaseOrderMapper.updateStatus(id, "REJECTED");
        
        // 重新查询订单以获取最新数据
        return purchaseOrderMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public PurchaseOrder closePurchaseOrder(Long id) {
        // 非空校验
        if (id == null) {
            throw new IllegalArgumentException("订单ID不能为空");
        }
        
        // 查找订单
        PurchaseOrder order = purchaseOrderMapper.selectById(id);
        if (order == null) {
            throw new RuntimeException("未找到订单，ID: " + id);
        }
        
        // 检查订单状态
        if (!"APPROVED".equals(order.getOrderStatus())) {
            throw new IllegalStateException("只有已审核状态的订单才能关闭");
        }
        
        // 更新订单状态
        purchaseOrderMapper.updateStatus(id, "CLOSED");
        
        // 重新查询订单以获取最新数据
        return purchaseOrderMapper.selectById(id);
    }
    
    /**
     * 计算订单总金额
     */
    private void calculateTotalAmount(PurchaseOrder purchaseOrder) {
        if (purchaseOrder.getOrderItems() != null && !purchaseOrder.getOrderItems().isEmpty()) {
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (PurchaseOrderItem item : purchaseOrder.getOrderItems()) {
                // 非空校验
                if (item.getQuantity() == null) {
                    throw new IllegalArgumentException("采购数量不能为空");
                }
                if (item.getUnitPrice() == null) {
                    throw new IllegalArgumentException("单价不能为空");
                }
                
                // 计算明细金额
                BigDecimal itemAmount = item.getQuantity().multiply(item.getUnitPrice());
                item.setAmount(itemAmount);
                
                // 累加总金额
                totalAmount = totalAmount.add(itemAmount);
            }
            purchaseOrder.setTotalAmount(totalAmount);
        } else {
            purchaseOrder.setTotalAmount(BigDecimal.ZERO);
        }
    }
}